package pub.cleangao.mybatis.spi;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pub.cleangao.common.util.JsonUtil;
import pub.cleangao.mybatis.runtime.Mode;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运行上下文
 */
public class SpiContext {

    /**
     * MyBatis 的SqlSessionFactory对象
     */
    private static final Map<DatabaseMeta, SqlSessionFactory> sqlSessionFactoryMap = new HashMap<>();

    public static BeanExecutor getBeanExecutor() {
        return new DefaultBeanExecutor();
    }


    /**
     * 设置全部的SqlSessionFactory
     */
    public static void setSqlSessionFactory(List<SqlSessionFactory> sqlSessionFactories) {
        if (sqlSessionFactories == null || sqlSessionFactories.isEmpty()) {
            return;
        }
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {

            SqlSession sqlSession = sqlSessionFactory.openSession();
            Connection connection = sqlSession.getConnection();
            try {
                DatabaseMetaData dbMetaData = connection.getMetaData();
                SpiContext.sqlSessionFactoryMap.put(new DatabaseMeta(dbMetaData.getURL()), sqlSessionFactory);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (Mode.DEBUG) {
            System.out.println("SqlSessionFactories: " + JsonUtil.pojoToJson(sqlSessionFactoryMap.keySet()));
        }
    }

    public static List<SqlSessionFactory> getSqlSessionFactories() {
        return new ArrayList<>(sqlSessionFactoryMap.values());
    }

    /**
     * 获取一个可用连接
     */
    public static Connection getConnection0() {
        if (sqlSessionFactoryMap.isEmpty()) {
            return null;
        }
        for (Map.Entry<DatabaseMeta, SqlSessionFactory> entry : sqlSessionFactoryMap.entrySet()) {
            return entry.getValue().openSession().getConnection();
        }
        return null;
    }
}
